<?php

namespace app\api\controller\market;

use app\api\controller\Controller;
use app\api\model\Recharge as RechargeModel;
use app\api\model\RechargePlan as RechargePlanModel;
use app\api\model\Wxapp as WxappModel;
use app\common\library\wechat\WxPayRechargr;

/**
 * 用户充值管理
 */
class Recharge extends Controller
{
    private $user;

    /**
     * 构造方法
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 充值支付
     */
    public function pay($money,$recharge_plan_id=0,$formId=0)
    {
		//如果是套餐充值，获取套餐赠送金额
		$data['gift_money'] = 0;//赠送金额
		if($recharge_plan_id>0){
			if($plan = RechargePlanModel::detail($recharge_plan_id)){
				if($money>=$plan['money']){
					$data['gift_money'] = $plan['gift_money'];
				}
			}else{
				return $this->renderError('套餐充值错误');
			}
		}
		// 创建订单
		$model = new RechargeModel;
		$data['money'] = $money;//充值金额
		$data['recharge_plan_id'] = $recharge_plan_id;//套餐id
		$data['user_id'] = $this->user_id;//用户id
		$data['order_no'] = $this->orderNo();//订单号
		$data['wxapp_id'] = $this->wxapp_id;
		$model->save($data);
        // 发起微信支付
        $wxConfig = WxappModel::getWxappCache();
        $WxPay = new WxPayRechargr($wxConfig);
        $wxParams = $WxPay->unifiedorder($data['order_no'], $this->user['open_id'], $money);
        return $this->renderSuccess($wxParams);
    }
	
	/**
     * 生成订单号
     */
    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}
